<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebRTC Live Stream - Receiver</title>
</head>

<body>
    <!-- 移除本地视频的元素 -->
    <!-- <video id="localVideo" autoplay muted playsinline></video> -->
    <video id="remoteVideo" autoplay playsinline></video>
    <input type="text" id="roomIdInput" placeholder="请输入房间号">
    <button id="joinRoomButton">加入房间</button>
    <script src="/socket.io/socket.io.js"></script>
</body>

</html>

<script>
    const socket = io();
    const remoteVideo = document.getElementById('remoteVideo');
    const roomIdInput = document.getElementById('roomIdInput');
    const joinRoomButton = document.getElementById('joinRoomButton');

    let peerConnection;
    let roomId;

    const configuration = {
        iceServers: [
            { urls: 'stun:stun.l.google.com:19302' },
            { urls: 'stun:stun1.l.google.com:19302' },
            { urls: 'stun:stun2.l.google.com:19302' }
        ]
    };

    // 创建 RTCPeerConnection
    async function createPeerConnection() {
        peerConnection = new RTCPeerConnection(configuration);

        peerConnection.onicecandidate = (event) => {
            if (event.candidate) {
                socket.emit('ice-candidate', roomId, event.candidate);
            }
        };

        peerConnection.ontrack = (event) => {
            remoteVideo.srcObject = event.streams[0];
        };
    }

    // 发起呼叫
    async function startCall() {
        await createPeerConnection();
        const offer = await peerConnection.createOffer();
        await peerConnection.setLocalDescription(offer);
        socket.emit('offer', roomId, offer);
    }

    // 处理接收到的 offer
    socket.on('offer', async (offer) => {
        console.log(offer);
        await createPeerConnection();
        await peerConnection.setRemoteDescription(offer);
        const answer = await peerConnection.createAnswer();
        await peerConnection.setLocalDescription(answer);
        socket.emit('answer', roomId, answer);
    });

    // 处理接收到的 answer
    socket.on('answer', async (answer) => {
        console.log(answer);
        await peerConnection.setRemoteDescription(answer);
    });

    // 处理接收到的 ICE 候选信息
    socket.on('ice-candidate', (candidate) => {
        console.log(candidate);
        peerConnection.addIceCandidate(new RTCIceCandidate(candidate));
    });

    // 加入房间
    joinRoomButton.addEventListener('click', async () => {
        roomId = roomIdInput.value;
        if (roomId) {
            socket.emit('join-room', roomId);
            await startCall();
        }
    });
</script>